<?php
/*
 * @Description:许可证附表管理
 * @FilePath: \auxface_certificate\app\certificate\controller\user\v1\MachineRiskSubForm.php
 */

declare(strict_types=1);

namespace app\certificate\controller\user\v1;

use DateTime;
use think\facade\Db;
use think\Request;

class MachineRiskSubForm
{
    /**
     * @Description: 获取许可证附表列表
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'];
        $page  = $data['page'];

        $searchWhere = [
            ['sf.riskUuid', '=', $data['riskUuid']],
        ];
        //当前用户待填写的表单
        $getCurrentToSubFormUuids = $this->getCurrentToSubFormUuids($request->uuid) ?: [];
        //状态,待审核-0,审核通过-1，已过期-2,待填写-3
        if (!empty($data['status']) || (isset($data['status']) && $data['status'] == 0)) {
            if ($data['status'] == 2) {
                array_push($searchWhere, ['sf.expiredTime', '<', date('Y-m-d H:i:s')]);
            } else if ($data['status'] == 3) {
                array_push($searchWhere, ['sf.status', '=', 0]);
                array_push($searchWhere, ['sf.expiredTime', '>', date('Y-m-d H:i:s')]);
            } else {
                array_push($searchWhere, ['sf.status', '=', $data['status']]);
                array_push($searchWhere, ['sf.expiredTime', '>', date('Y-m-d H:i:s')]);
            }

            //数据隔离
            if ($data['status'] == 3) {
                array_push($searchWhere, ['sf.uuid', 'IN', $getCurrentToSubFormUuids]);
            } else {
                //获取当前提交过的许可证附表
                // $subFormUuids = DB::table('certificate_machineRiskSubFormRecord')->where('wxappUserUuid', $request->uuid)->group('subFormUuid')->column('subFormUuid') ?? [];
                // array_push($searchWhere, ['sf.uuid', 'IN', $subFormUuids]);
            }
        }
        if (!empty($data['typeUuid'])) array_push($searchWhere, ['sf.subFormUuid', '=', $data['typeUuid']]);
        $list = DB::table('certificate_machineRiskSubForm')
            ->alias('sf')
            ->join('certificate_subform s', 's.uuid=sf.subFormUuid')
            ->join('certification_projectWorker wi', 'wi.wxappUserUuid = sf.wxappUserUuid', 'left')
            ->where($searchWhere)
            ->field(['sf.uuid', 'wi.workerName', 's.name as typeName', 'sf.inDate', 'sf.uuid', 'sf.status', 'sf.expiredTime'])
            ->order('sf.id desc')
            ->page((int)$page, (int)$limit)
            ->group('sf.id')
            ->select();
        $result['list'] = $list;
        //是否有新增权限
        $result['hasAuth'] =  0;
        //待填写数量
        $result['toSubCount'] = $this->getToSubCount($getCurrentToSubFormUuids, $data);
        //是否有新增权限,具有申请表权限+驾驶舱人员
        $result['hasAuth'] = $this->hasAuth($request, $data);
        return result(SUCCESS, $result, '');
    }

    /**
     * 获取许可证附表详情
     *
     * @param Request $request
     * @return void
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $where = [
            'sf.uuid' => $uuid
        ];
        //查看有没有提交过的记录
        $subFormData = DB::table('certificate_machineRiskSubForm')
            ->alias('sf')
            ->join('certificate_subform s', 's.uuid=sf.subFormUuid')
            ->where($where)
            ->order('sf.id DESC')
            ->field(['sf.expiredTime', 'sf.status', 'sf.uuid', 's.name as typeName'])
            ->findOrEmpty();
        if (!$subFormData) return result(FAIL, '', '獲取失敗，請返回重試');
        $getCurrentToSubFormUuids = [];
        if($subFormData['status']!=1) $getCurrentToSubFormUuids = $this->getCurrentToSubFormUuids($request->uuid);
        if (strtotime($subFormData['expiredTime']) < time()) {
            $subFormData['status'] = '2'; //已过期
        } else if (in_array($subFormData['uuid'], $getCurrentToSubFormUuids)) {
            $subFormData['status'] = '3'; //待提交
        }
        $record = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_machineRiskSubFormRecord r', 'r.flowFormUuid = ff.uuid')
            ->where('r.subFormUuid', $uuid)
            ->order('ff.flowOrder asc')
            ->field('ff.uuid,ff.name,r.formData,ff.subtitle')
            ->group('ff.uuid')
            ->select()->toArray();
        foreach ($record as $key => $item) {
            $record[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
        }
        $subFormData['riskRecord'] = $record;
        $canSubFormUUids = $this->canSubForm($subFormData['uuid']);
        $subFormData['hasNext'] =  $subFormData['hasAuth'] = 0;
        $subFormData['currentData'] = $subFormData['nextData'] = [];
        //获取当前用户拥有的表单信息
        $currentFormData = DB::table('certificate_flowForm')
            ->alias('ff')
            ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
            ->where('fw.wxappUserUuid', $request->uuid)
            ->whereIn('ff.uuid', $canSubFormUUids)
            ->where('fw.isDelete', 0)
            ->order('ff.flowOrder asc')
            ->field('ff.uuid as formUuid,ff.name,ff.subtitle,ff.formData,ff.linkForms,ff.type,ff.flowUuid,ff.flowOrder')
            ->find();
        if ($currentFormData) {
            $currentData['formData']['uuid'] = $currentFormData['formUuid'];
            $currentData['formData']['name'] = $currentFormData['name'];
            $currentData['formData']['subtitle'] = $currentFormData['subtitle'];
            $currentData['formData']['formData'] = json_decode(html_entity_decode($currentFormData['formData']), true);
            $linkForms = $currentFormData['linkForms'] ? json_decode($currentFormData['linkForms'], true) : [];
            if ($linkForms) {
                $linkForms = DB::table('certificate_flowForm')
                    ->alias('ff')
                    ->join('certificate_machineRiskSubFormRecord r', 'r.flowFormUuid = ff.uuid')
                    ->where(['r.subFormUuid'=>$uuid])
                    ->whereIn('ff.uuid', $linkForms)
                    ->order('ff.showOrder asc,ff.flowOrder asc,r.id asc')
                    ->field('ff.uuid,ff.name,r.formData')
                    ->group('ff.uuid')
                    ->select()->toArray();
                foreach ($linkForms as $key => $item) {
                    $linkForms[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
                }
            }

            //是否有下一次提交
            $canNextSubFormUUids = $this->canSubForm($uuid, 0, $currentFormData['flowUuid'], $currentFormData['formUuid'], $currentFormData['flowOrder'], $currentFormData['type']);
            $nextFormData = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
                ->where('fw.wxappUserUuid', $request->uuid)
                ->whereIn('ff.uuid', $canNextSubFormUUids)
                ->where('fw.isDelete', 0)
                ->find();
            if ($nextFormData) {
                $subFormData['hasNext'] = 1;
                $subFormData['nextData'] = $nextFormData;
            }

            $currentData['linkForms'] = $linkForms;
            $subFormData['currentData'] = $currentData;
            $subFormData['hasAuth'] = 1;
        }

        return result(SUCCESS, $subFormData, '');
    }

    /**
     * @Description: 设备许可证附表申请
     * @param {Request} $request
     */
    public function apply(Request $request)
    {
        $data  = $request->data;
        
        
        $wxappUserUuid = $request->uuid;

        $subFormTypeUuid = $data['subFormTypeUuid'];
        $riskUuid = $data['riskUuid'];
        $formData = html_entity_decode(is_array($data['formData']) ? json_encode($data['formData'], JSON_UNESCAPED_UNICODE) : $data['formData']);
        $type = DB::table('certificate_subForm')->where(['isDelete' => 0, 'uuid' => $subFormTypeUuid])->find();
        if (!$type)  return result(FAIL, '', '附表类型已被删除或错误！');

        $flowForm = Db::table('certificate_flowForm')->where('uuid', $data['flowFormUuid'])->find();
        if (!$flowForm) return result(FAIL, '', '流程表单不存在');

        //是否有申请权限
        $searchWhere = [
            ['sf.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['ff.formType', '=', 1],
            ['fw.isDelete', '=', 0],
            ['ff.uuid', '=', $data['flowFormUuid']],
        ];
        $auth = DB::table('certificate_subForm')
            ->alias('sf')
            ->join('certificate_flowForm ff', 'ff.flowUuid=sf.flowUuid')
            ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
            ->where($searchWhere)
            ->find();
        if (empty($auth)) return result(FAIL, '', '您没有申请权限');

        $machineRisk = DB::table('certificate_machineRisk')->where(['uuid' => $riskUuid])->find();
        if (empty($machineRisk)) {
            return result(FAIL, '', '许可证不存在');
        } else if ($machineRisk['status'] != 1 || (strtotime($machineRisk['expiredTime']) < time())) {
            return result(FAIL, '', '许可证状态错误,只有使用中的许可证才能申请附表');
        }

        //流程是否正在进行中
        $isPending = DB::table('certificate_machineRisk')->where(['isDelete' => 0, 'flowUuid' => $flowForm['flowUuid'], 'status' => 0])->where([['expiredTime', '>', date('Y-m-d H:i:s')]])->find();
        if ($isPending) {
            // return result(FAIL, '', "流程【{$flowForm['name']}】正在进行中，不允许重新申请");
        }

        DB::startTrans();
        try {
            $expiredTime = $data['expiredTime'] ?? 'now';
            // 获取当前日期
            $dateTime = new DateTime($expiredTime);
            // 获取当前周的周日日期
            $dateTime->modify('sunday this week');  // 获取本周的周日
            $expiredTime = $dateTime->format('Y-m-d');  // 格式化为 YYYY-MM-DD

            //设备许可证附表记录
            $subFormData = [
                'riskUuid'      => $riskUuid,
                'subFormUuid'   => $subFormTypeUuid,
                'flowFormUuid'  => $data['flowFormUuid'],
                'flowUuid'      => $flowForm['flowUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'status'        => 0,
                'uuid'          => createUuid(),
                'expiredTime'   => $expiredTime . ' 23:59:59',
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
            ];

            DB::table('certificate_machineRiskSubForm')->insert($subFormData);

            //提交表单记录
            $recordData = [
                'subFormUuid'   => $subFormData['uuid'],
                'riskUuid'      => $riskUuid,
                'flowFormUuid'  => $data['flowFormUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'flowOrder'     => $flowForm['flowOrder'],
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
                'checkDate'     => $data['checkDate'] ?? date('Y-m-d'),
            ];
            DB::table('certificate_machineRiskSubFormRecord')->insert($recordData);

            $updateData = [];
            //判断是否已经全部流程完成了
            $isFinish = $this->isFinish($subFormData['uuid']);
            if ($isFinish) {
                $updateData['status'] = 1;
                $updateData['auditTime'] = date('Y-m-d H:i:s');
            } else {
                //记录下一个可填写的表单
                $canSubForm = $this->canSubForm($subFormData['uuid']) ?: [];
                $updateData['nextFlowFormUuids'] = json_encode($canSubForm, JSON_UNESCAPED_UNICODE);
            }
            DB::table('certificate_machineRiskSubForm')->where('uuid', $subFormData['uuid'])->update($updateData);

            DB::commit();
            return result(SUCCESS, ['uuid' => $subFormData['uuid']], '');
        } catch (\Exception $e) {
            return result(FAIL, '', $e->getMessage());
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    /**
     * @Description: 表单审核
     * @param {Request} $request
     */
    public function audit(Request $request)
    {
        $data  = $request->data;
        $wxappUserUuid = $request->uuid;

        $uuid = $data['uuid'];
        $formData = html_entity_decode($data['formData']);
        $subForm = DB::table('certificate_machineRiskSubForm')->where(['uuid' => $uuid])->find();
        if (!$subForm)  return result(FAIL, '', '许可证申请记录不存在！');
        if ($subForm['status'] == 1) return result(FAIL, '', '该许可证已审核通过');

        //是否有审核权限
        $searchWhere = [
            ['rt.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['ff.formType', '=', 2],
            ['fw.isDelete', '=', 0],
            ['ff.uuid', '=', $data['flowFormUuid']],
        ];
        $auth = DB::table('certificate_subForm')
            ->alias('rt')
            ->join('certificate_flow f', 'f.uuid=rt.flowUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
            ->where($searchWhere)
            ->find();
        if (empty($auth)) return result(FAIL, '', '您没有审核权限');

        DB::startTrans();
        try {
            $flowForm = Db::table('certificate_flowForm')->where('uuid', $data['flowFormUuid'])->find();
            if (!$flowForm) return result(FAIL, '', '流程表单不存在');

            //提交表单记录
            $recordData = [
                'subFormUuid'   => $subForm['uuid'],
                'riskUuid'      => $subForm['riskUuid'],
                'flowFormUuid'  => $data['flowFormUuid'],
                'wxappUserUuid' => $wxappUserUuid,
                'uuid'          => createUuid(),
                'formData'      => $formData,
                'flowOrder'     => $flowForm['flowOrder'],
                'projectCode'   => $request->prjCode,
                'corpCode'      => $request->corpCode,
                'checkDate' => $data['checkDate'] ?? date('Y-m-d'),
            ];
            DB::table('certificate_machineRiskSubFormRecord')->insert($recordData);

            $updateData = [];
            //判断是否已经全部流程完成了
            $isFinish = $this->isFinish($subForm['uuid']);
            if ($isFinish) {
                $updateData['status'] = 1;
                $updateData['auditTime'] = date('Y-m-d H:i:s');
            } else {
                //记录下一个可填写的表单
                $canSubForm = $this->canSubForm($subForm['uuid']) ?: [];
                $updateData['nextFlowFormUuids'] = json_encode($canSubForm, JSON_UNESCAPED_UNICODE);
            }
            DB::table('certificate_machineRiskSubForm')->where('uuid', $subForm['uuid'])->update($updateData);
            DB::commit();
            return result(SUCCESS, ['uuid' => $recordData['uuid']], '提交成功');
        } catch (\Exception $e) {
            DB::rollback();
        }
        return result(FAIL, '', '提交失败,请重试');
    }

    //本流程下待填写表单
    public function canSubForm($uuid, $isNext = 1, $flowUuid = '', $lastFlowFormUuid = '', $lastFlowOrder = 1, $lastType = 1)
    {
        //是否直接获取下一个表单
        if ($isNext) {
            //获取最近一个已填写的表单记录
            $record = DB::table('certificate_machineRiskSubFormRecord')
                ->alias('rr')
                ->join('certificate_machineRiskSubForm sf', 'sf.uuid = rr.subFormUuid')
                ->join('certificate_flowForm ff', 'ff.uuid = rr.flowFormUuid')
                ->where([
                    ['rr.subFormUuid', '=', $uuid]
                ])
                ->field('rr.flowOrder,sf.flowUuid,sf.expiredTime,ff.type,rr.flowFormUuid')
                ->order('rr.flowOrder desc,rr.id desc')  // 按照流程顺序降序排列
                ->find();

            if (!$record) {
                return [];
            }
            $flowUuid         = $record['flowUuid'];
            $lastFlowFormUuid = $record['flowFormUuid'];
            $lastFlowOrder    = $record['flowOrder'];
            $lastType         = $record['type'];
        }

        $nextFlowOrder = $lastFlowOrder + 1;
        $canSubFormUUids = [];
        // 获取流表单数据
        $flowForms = DB::table('certificate_flowForm')
            ->where('flowUuid', '=', $flowUuid)
            ->where('isDelete', '=', 0)
            ->whereIn('flowOrder', [$lastFlowOrder, $nextFlowOrder])
            ->where('uuid', '<>', $lastFlowFormUuid)
            ->field(['uuid', 'flowOrder', 'signType'])
            ->select()
            ->toArray();
        // 处理流表单
        if (!empty($flowForms)) {
            $formUuids = array_column($flowForms, 'uuid');
            $signTypes = array_column($flowForms, 'signType');
            // 有多个表单并且存在 signType 1
            if (count($flowForms) > 1 && in_array(1, $signTypes)) {
                // 剔除当前的 lastFlowFormUuid
                $canSubFormUUids = array_filter($formUuids, function ($uuid) use ($lastFlowFormUuid) {
                    return $uuid !== $lastFlowFormUuid;
                });
            } else {
                $canSubFormUUids = $formUuids; // 直接取所有的 UUID
            }
            // 如果没有 signType 为 1
            if (!in_array(1, $signTypes)) {
                $nextFlowUuids = array_column(
                    array_filter($flowForms, function ($form) use ($nextFlowOrder) {
                        return $form['flowOrder'] == $nextFlowOrder;
                    }),
                    'uuid'
                );
                $canSubFormUUids = array_unique(array_merge($canSubFormUUids, $nextFlowUuids));
            }
        }

        //如果类型是周表
        if ($lastType == 1) {
            //判断是否已经完成了7天的数据
            $count = DB::table('certificate_machineRiskSubFormRecord')->where([
                ['flowFormUuid', '=', $record['flowFormUuid']]
            ])->count();
            if ($count != 7 && strtotime($record['expiredTime']) > strtotime(date('Y-m-d 23:59:59'))) {
                $canSubFormUUids[] = $record['flowFormUuid'];
            }
        }
        return $canSubFormUUids;
    }

    /**
     * @Description: 获取附表类型列表
     * @param {Request} $request
     */
    public function getSubFormTypeList(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $riskType = DB::table('certificate_machineRisk')->alias('r')
            ->join('certificate_machineRiskType rt', 'rt.uuid = r.typeUuid')
            ->where('r.uuid', $uuid)
            ->field('rt.subFormUuids')
            ->find();
        if (!$riskType) return result(FAIL, '', '类型不存在');
        $subFormUuids = $riskType['subFormUuids'] ? json_decode($riskType['subFormUuids'], true) : [];
        if (!$subFormUuids) return result(FAIL, '', '獲取失敗，請返回重試');

        $searchWhere = [
            ['sf.uuid', 'IN', $subFormUuids],
            ['sf.isDelete', '=', 0],
            ['ff.formType', '=', 1],
        ];
        $list = DB::table('certificate_subForm')
            ->alias('sf')
            ->join('certificate_flowForm ff', 'ff.flowUuid=sf.flowUuid')
            ->order(['sf.id desc'])
            ->where($searchWhere)
            ->field(['sf.name', 'sf.uuid', 'sf.subtitle'])
            ->distinct(true)
            ->select()->toArray();

        return result(SUCCESS, $list, '');
    }

    /**
     * 获取附表类型详情
     *
     * @param Request $request
     * @return void
     */
    public function getSubFormTypeDetail(Request $request)
    {
        $data = $request->data;
        $where = [
            'sf.uuid' => $data['uuid'],
            'ff.formType' => 1
        ];
        $typeData = DB::table('certificate_subForm')
            ->alias('sf')
            ->join('certificate_flow f', 'f.uuid=sf.flowUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->where($where)
            ->field(['ff.formData', 'sf.name', 'sf.uuid', 'ff.uuid as formUuid', 'ff.name as formName'])
            ->find();
        if (empty($typeData)) return result(FAIL, '', '獲取失敗，請返回重試');
        $typeData['formData'] = json_decode(html_entity_decode($typeData['formData'] ?? ''), true) ?: [];
        //获取是否有下一步按钮
        $typeData['hasNext'] = $this->hasNextBySubFormUuid($typeData['uuid'], $request->uuid);
        return result(SUCCESS, $typeData, '');
    }

    //本流程是否已经完成
    public function isFinish($subFormUuid)
    {
        $isFinish = 0;
        //获取最近一个已填写的表单记录
        $record = DB::table('certificate_machineRiskSubFormRecord')
            ->alias('rr')
            ->join('certificate_machineRiskSubForm r', 'r.uuid = rr.subFormUuid')
            ->join('certificate_flowForm ff', 'ff.uuid = rr.flowFormUuid')
            ->where([
                ['rr.subFormUuid', '=', $subFormUuid]
            ])
            ->order('rr.flowOrder desc,rr.id desc')  // 按照流程顺序降序排列
            ->find();

        if (!$record) {
            return 0 ;
            // return result(FAIL, '', '没有许可证附表提交记录');
        }
        $nextFlowOrder = $record['flowOrder'] + 1;
        $canSubFormUUids = [];
        $flowForm = DB::table('certificate_flowForm')
            ->where([
                ['flowUuid', '=', $record['flowUuid']],
                ['isDelete', '=', 0],
                ['flowOrder', '=', $record['flowOrder']],
            ])->select()->toArray();
        $recordCount = DB::table('certificate_machineRiskRecord')
            ->alias('rr')
            ->join('certificate_machineRisk r', 'r.uuid = rr.riskUuid')
            ->where([
                ['r.flowUuid', '=', $record['flowUuid']],
                ['rr.isDelete', '=', 0],
                ['rr.flowOrder', '=', $record['flowOrder']],
            ])->count();
        if (count($flowForm) > 1 && in_array(1, array_column($flowForm, 'signType')) && $recordCount != count($flowForm)) {
            $canSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $record['flowOrder']],
                    ['uuid', '<>', $record['flowFormUuid']]
                ])->column('uuid');
        } else {
            $canSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $nextFlowOrder],
                ])->column('uuid');
        }
        if (!$canSubFormUUids)  $isFinish = 1;
        return $isFinish;
    }

    /**
     * @Description: 根据许可证类型获取附表类型列表
     * @param {Request} $request
     */
    public function getSubFormTypeListByRiskType(Request $request)
    {
        $data = $request->data;
        $typeUuid = $data['typeUuid'];

        $risk = DB::table('certificate_machineRiskType')->where('uuid', $typeUuid)->find();
        if (empty($risk)) {
            return result(FAIL, '', '獲取失敗，請返回重試');
        }
        $subFormUuids = $risk['subFormUuids'] ? json_decode($risk['subFormUuids'], true) : [];
        if (!$subFormUuids) {
            return result(FAIL, '', '獲取失敗，請返回重試');
        }

        $searchWhere = [
            ['sf.uuid', 'IN', $subFormUuids],
            ['sf.isDelete', '=', 0],
        ];
        $list = DB::table('certificate_subForm')
            ->alias('sf')
            ->join('certificate_flowForm ff', 'ff.flowUuid=sf.flowUuid')
            ->order(['sf.id desc'])
            ->where($searchWhere)
            ->field(['sf.name', 'sf.uuid', 'sf.subtitle'])
            ->distinct(true)
            ->select()->toArray();

        return result(SUCCESS, $list, '');
    }

    /**
     * @Description: 根据许可证类型获取附件类型列表
     * @param {Request} $request
     */
    public function getFileTypeListByRiskType(Request $request)
    {
        $data = $request->data;
        $typeUuid = $data['typeUuid'];

        $risk = DB::table('certificate_machineRiskType')->where('uuid', $typeUuid)->find();
        if (empty($risk)) {
            return result(FAIL, '', '獲取失敗，請返回重試');
        }
        $fileTypeUuids = $risk['fileTypeUuids'] ? json_decode($risk['fileTypeUuids'], true) : [];
        if (!$fileTypeUuids) {
            return result(FAIL, '', '獲取失敗，請返回重試');
        }

        $searchWhere = [
            ['ft.uuid', 'IN', $fileTypeUuids],
            ['ft.isDelete', '=', 0],
        ];
        $list = DB::table('certificate_fileType')
            ->alias('ft')
            ->order(['ft.id desc'])
            ->where($searchWhere)
            ->field(['ft.name', 'ft.uuid'])
            ->distinct(true)
            ->select()->toArray();

        return result(SUCCESS, $list, '');
    }

    //获取当前用户待提交表单的许可证附表
    public function getCurrentToSubFormUuids($wxappUserUuid)
    {
        $flowFormUuid = DB::table('certificate_machineRiskRecord')
            ->alias('r')
            ->join('certificate_machineRisk mr', 'mr.uuid =  r.riskUuid')
            ->where('r.wxappUserUuid', $wxappUserUuid)
            ->where('mr.status', 0)
            ->where('mr.expiredTime', '>', date('Y-m-d H:i:s'))
            ->column('r.flowFormUuid') ?? [];
        //获取当前用户拥有的表单
        $flowFormUuids = DB::table('certificate_flowFormWorker')
            ->alias('w')
            ->join('certificate_flowForm ff', 'w.flowFormUuid=w.flowFormUuid')
            ->where('w.wxappUserUuid', $wxappUserUuid)
            ->where('ff.formType', 2)
            ->where('w.isDelete', 0)
            ->whereNotIn('ff.uuid', $flowFormUuid)
            ->group('w.flowFormUuid')
            ->column('w.flowFormUuid') ?: [];
        $arrList =  DB::table('certificate_machineRiskSubForm')->where('nextFlowFormUuids', '<>', '')->field(['uuid', 'nextFlowFormUuids'])->select()->toArray();
        $arrList = array_filter($arrList, function ($item) use ($flowFormUuids) {
            $nextFlowFormUuids = json_decode($item['nextFlowFormUuids'], true);
            if (array_intersect($flowFormUuids, $nextFlowFormUuids)) {
                return true;
            }
            return false;
        });
        return array_column($arrList, 'uuid') ?: [];
    }

    public function hasNextBySubFormUuid($subFormUuid, $wxappUserUuid)
    {
        $hasNext = 0;
        $where = [
            'sf.isDelete' => 0,
            'sf.uuid' => $subFormUuid,
            'ff.formType' => 1,
            'ff.isDelete' => 0
        ];
        $record = DB::table('certificate_subForm')
            ->alias('sf')
            ->join('certificate_flow f', 'f.uuid=sf.flowUuid')
            ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
            ->where($where)
            ->field(['sf.uuid', 'ff.flowUuid', 'ff.uuid as flowFormUuid', 'ff.type'])
            ->find();
        if ($record) {
            //本流程下可提交的表单
            $nextFlowOrder = 2;
            $canSubFormUUids = [];
            //如果类型是周表
            if ($record['type'] == 1) {
                // 获取当前日期
                $today = new DateTime();
                // 获取当前周的周日日期
                $endOfWeek = clone $today;
                $endOfWeek->modify('sunday this week');  // 获取本周的周日
                // 以 YYYY-MM-DD 格式输出日期
                $weekEndDate = $endOfWeek->format('Y-m-d');  // 格式化为 YYYY-MM-DD
                if (strtotime($weekEndDate . ' 23:59:59') > strtotime(date('Y-m-d 23:59:59'))) {
                    $canSubFormUUids[] = $record['flowFormUuid'];
                }
            }
            $canNextSubFormUUids = DB::table('certificate_flowForm')
                ->where([
                    ['flowUuid', '=', $record['flowUuid']],
                    ['isDelete', '=', 0],
                    ['flowOrder', '=', $nextFlowOrder],
                ])->column('uuid');
            $canSubFormUUids = array_merge($canSubFormUUids, $canNextSubFormUUids);
            //获取当前用户拥有的表单信息
            $nextData = DB::table('certificate_flowForm')
                ->alias('ff')
                ->join('certificate_flowFormWorker fw', 'fw.flowFormUuid = ff.uuid')
                ->where([
                    'fw.wxappUserUuid' => $wxappUserUuid,
                    'fw.isDelete' => 0
                ])
                ->whereIn('ff.uuid', $canSubFormUUids)
                ->order('ff.flowOrder asc')
                ->field('ff.uuid')
                ->find();
            if ($nextData) $hasNext = 1;
        }
        return $hasNext;
    }

    public function getToSubCount($getCurrentToSubFormUuids, $data)
    {
        //待填写数量
        $searchWhere = [];
        array_push($searchWhere, ['sf.riskUuid', '=',  $data['riskUuid']]);
        array_push($searchWhere, ['sf.uuid', 'IN', $getCurrentToSubFormUuids]);
        array_push($searchWhere, ['sf.status', '=', 0]);
        array_push($searchWhere, ['sf.expiredTime', '>', date('Y-m-d H:i:s')]);
        array_push($searchWhere, ['w.isDelete', '=', 0]);
        if (!empty($data['machineUuid'])) array_push($searchWhere, ['sf.machineUuid', '=', $data['machineUuid']]);
        if (!empty($data['areaUuid'])) array_push($searchWhere, ['sf.areaUuid', '=', $data['areaUuid']]);
        if (!empty($data['typeUuid'])) array_push($searchWhere, ['sf.subFormUuid', '=', $data['typeUuid']]);
        $toSubCount =  DB::table('certificate_machineRiskSubForm')
            ->alias('sf')
            ->join('certificate_subform s', 's.uuid=sf.subFormUuid')
            ->join('certificate_flowFormWorker w', 'w.wxappUserUuid = sf.wxappUserUuid')
            ->where($searchWhere)
            ->group('sf.id')
            ->count();
        return $toSubCount ?: 0;
    }

    public function hasAuth($request, $data)
    {
        //是否有新增权限,具有申请表权限+驾驶舱人员
        $hasAuth =  0;
        $searchWhere = [
            ['sf.projectCode', '=', $request->prjCode],
            ['fw.wxappUserUuid', '=', $request->uuid],
            ['sf.isDelete', '=', 0],
            ['fw.isDelete', '=', 0],
            ['ff.formType', '=', 1],
        ];
        if (!empty($data['machineUuid'])) {
            array_push($searchWhere, ['m.uuid', '=', $data['machineUuid']]);
        }

        $machineRisk = DB::table('certificate_machineRisk')->alias('r')
            ->join('certificate_machineRiskType rt', 'rt.uuid = r.typeUuid')
            ->join('certificate_digitalMachineType mt', 'rt.uuid=mt.machineRiskTypeUuid')
            ->join('certificate_digitalMachine m', 'm.digitalMacineTypeUuid=mt.uuid')
            ->join('certificate_digitalMachineDriver d', 'd.digitalMachineUuid = m.uuid')
            ->where('r.uuid', $data['riskUuid'])
            ->where('d.wxappUserUuid', $request->uuid)
            ->where('m.status', 1)
            ->field('rt.subFormUuids,r.status,r.expiredTime')
            ->find() ?: [];
        if ($machineRisk && $machineRisk['status'] == 1 && strtotime($machineRisk['expiredTime']) > time()) {
            $subFormUuids = json_decode($machineRisk['subFormUuids'] ?? [], true);
            array_push($searchWhere, ['sf.uuid', 'IN', $subFormUuids]);
            $auth = DB::table('certificate_subForm')
                ->alias('sf')
                ->join('certificate_flow f', 'f.uuid=sf.flowUuid')
                ->join('certificate_flowForm ff', 'ff.flowUuid=f.uuid')
                ->join('certificate_flowFormWorker fw', 'ff.uuid=fw.flowFormUuid')
                ->where($searchWhere)
                ->find();
            if (!empty($auth)) $hasAuth =  1;
        }
        return $hasAuth;
    }
}
